package com.dqhl.community.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.User;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.FormatUtils;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.TimeCountUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * Created by cheng on 2016/9/27.
 * 第三方登陆绑定手机号
 */
public class BindingPhoneActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private EditText et_phone;
    private EditText et_code;
    private Button btn_get_code;
    private Button btn_submit;
    private long millisInFuture = Constant.TIMECOUNT_MODIFY_PHONE; //验证码倒计时
    private String thirdId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_phone);

        initView();
    }

    private void initView() {
        thirdId = getIntent().getStringExtra("id");

        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText("绑定手机号");
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_code = (EditText) findViewById(R.id.et_code);
        btn_get_code = (Button) findViewById(R.id.btn_get_code);
        btn_submit = (Button) findViewById(R.id.btn_submit);

        ivTopBack.setOnClickListener(this);
        btn_get_code.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.btn_get_code: //获取验证码
                doGetCode();
                break;
            case R.id.btn_submit: //绑定手机
                doSubmit();
                break;
        }
    }

    /**
     * 提交
     */
    private void doSubmit() {
        String strPhone = et_phone.getText().toString();
        String strCode = et_code.getText().toString();
        if (strPhone.equals("") || strPhone.length() <= 0) {
            toast(R.string.toast_telephone_null);
        } else if (!FormatUtils.isMobileNO(strPhone)) {
            toast("手机格式不正确");
        } else if (strCode.equals("") || strCode.length() <= 0) {
            toast("验证码不能为空");
        } else {
            RequestParams params = new RequestParams(Config.Api.third_binding);
            params.addBodyParameter("phone", strPhone);
            params.addBodyParameter("code", strCode);
            params.addBodyParameter("id", thirdId);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("result:" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    String data = JsonUtils.getInfo(result, "data");
                    String errMsg = JsonUtils.getInfo(result, "errMsg");
                    if (errCode == 0) {
                        toast("绑定成功");
                        User user = JSON.parseObject(data, User.class);
                        String userid = user.getUserid();
                        String authentication = user.getAuthentication();
                        String community_id = user.getCommunity_id();
                        String building_id = user.getBuilding_id();
                        String unit_id = user.getUnit_id();
                        String residence_id = user.getResidence_id();
                        String address = community_id + building_id + unit_id + residence_id;
                        String sex = user.getSex();
                        String nickname = user.getNickname();
                        String head_img = user.getHead();
                        String name = user.getName();
                        String phone = user.getPhone();
                        String wxstate = user.getWxstate();
                        String qqstate = user.getQqstate();
                        // 将user信息放到application中
                        app.setUserId(userid);
                        app.setAuthentication(authentication);

                        // 将userid放到SharedPreferences中
                        SharedPreferences.Editor editor = spUserInfo.edit();
                        editor.putString(Constant.USER_PHONE, phone);
                        editor.putString(Constant.USERID, userid);
                        editor.putString(Constant.NICKNAME, nickname);
                        editor.putString(Constant.AUTHENTICATION, authentication);
                        editor.putString(Constant.COMMUNITY_ID, community_id);
                        editor.putString(Constant.ADDRESS, address);
                        editor.putString(Constant.SEX, sex);
                        editor.putString(Constant.PHOTO_PATH, head_img);
                        editor.putString(Constant.NAME, name);
                        editor.putString(Constant.WXSTATE, wxstate);
                        editor.putString(Constant.QQSTATE, qqstate);
                        editor.apply();
                        Dlog.e("userid:" + userid);

                        sendLoginSuccessBroadCast();
                        finish();
                    } else if (errCode == 4035) {
                        toast(errMsg);
                    } else {
                        toast("绑定失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    /**
     * 发送一个登录成功的广播
     */
    private void sendLoginSuccessBroadCast() {
        Intent intent = new Intent(Constant.ACTION_LOGIN_SUCCESS);
        intent.putExtra(Constant.USER_PHONE, spUserInfo.getString(Constant.USER_PHONE, ""));
        sendBroadcast(intent);
    }

    /**
     * 获取验证码
     */
    private void doGetCode() {
        String strPhone = et_phone.getText().toString();
        if (strPhone.equals("") || strPhone.length() <= 0) {
            toast(R.string.toast_telephone_null);
        } else if (!FormatUtils.isMobileNO(strPhone)) {
            toast("手机格式不正确");
        } else {
            TimeCountUtil timeCountUtil = new TimeCountUtil(
                    BindingPhoneActivity.this, millisInFuture, 1000, btn_get_code);
            timeCountUtil.start();

            RequestParams params = new RequestParams(Config.Api.verification);
            params.addBodyParameter("phone", strPhone);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("result:" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    String data = JsonUtils.getInfo(result, "data");
                    if (errCode == 0) {
                        String code = JsonUtils.getInfo(data, "code");
                        Dlog.e("验证码：" + code);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }
}
